# -*- coding: utf-8 -*-
import requests
import ConfigParser
import sys
import json

reload(sys)
sys.setdefaultencoding('utf8')

cfg = ConfigParser.ConfigParser()
cfg.read('conf/config.txt')

DATABASE_URL = cfg.get('default', 'database_url')

ERROR_SUCCESS = 'OK'

ERRCODE_DUPLICATE = -1
ERRCODE_NOTEXIST = -1


def query_default(category, appid, user_id, questions):
    payload = {'op': 'query',
               'appid': appid,
               'category': category,
               'userRecordId': user_id,
               'data': {}}

    entities = list()
    result_dict = {'status': 'false', 'data': {}, 'desc': '', 'invalid': {}}
    record_dict = dict()
    invalid_dict = dict()
    for q in questions:
        entity_dict = {'content': q}
        entities.append(entity_dict)

    payload['data']['entities'] = entities
    r = requests.post(DATABASE_URL, data=json.dumps(payload))
    jdata = r.json()

    results = jdata.get('actualResults')

    for index, result in enumerate(results):
        if not 'recordId' in result.keys():
            recordid = ERRCODE_NOTEXIST
            content = questions[index]
            invalid_dict[content] = recordid
        else:
            recordid = result.get('recordId')
            content = result.get('content')
            record_dict[content] = recordid

    if len(invalid_dict.keys()):
        result_dict['desc'] = 'Question:<br>'
        for index, invalid in enumerate(invalid_dict.keys()):
            result_dict['desc'] += str(index+1) + '. ' + invalid + '<br>'
        result_dict['desc'] += '数据库内不存在'

    result_dict['status'] = 'true'
    result_dict['data'] = record_dict
    result_dict['invalid'] = invalid_dict
    return result_dict


def query_conditions(category, appid, userid, conditions={}):
    payload = {'op': 'query',
               'appid': appid,
               'category': category,
               'userRecordId': userid,
               'data': {'subop': 'conditionsSubop'}}

    if category != 'sq':
        payload['data']['conditions'] = conditions

    # print json.dumps(payload, ensure_ascii=False, indent=4)
    result_dict = {'status': 'false', 'data': {}, 'desc': '', 'invalid': {}}
    record_dict = dict()
    r = requests.post(DATABASE_URL, data=json.dumps(payload))
    jdata = r.json()
    # print json.dumps(jdata, ensure_ascii=False, indent=4)
    results = jdata.get('actualResults')
    for result in results:
        if not 'recordId' in result.keys():
            continue
        else:
            recordid = result.get('recordId')
            content = result.get('content')
            record_dict[content] = recordid

    result_dict['status'] = 'true'
    result_dict['data'] = record_dict
    return result_dict


def insert_questions(category, appid, userid, entities):
    payload = {'op': 'insert',
               'category': category,
               'appid': appid,
               'userRecordId': userid,
               'data': {}}

    result_dict = {'status': 'false', 'data': {}, 'desc': '', 'invalid': {}}
    record_dict = dict()
    invalid_dict = dict()
    tmp_list = list()

    payload['data']['entities'] = entities
    r = requests.post(DATABASE_URL, data=json.dumps(payload))
    jdata = r.json()
    results = jdata.get('actualResults')
    for index, recordid in enumerate(results):
        content = entities[index].get('content')
        if recordid == ERRCODE_DUPLICATE:
            invalid_dict[content] = recordid
        else:
            record_dict[content] = recordid

    if len(invalid_dict.keys()):
        result_dict['desc'] = 'Question:<br>'
        for index, invalid in enumerate(invalid_dict.keys()):
            result_dict['desc'] += str(index+1) + '. ' + invalid + '<br>'
        result_dict['desc'] += '数据库内已经存在，未导入成功'

    result_dict['status'] = 'true'
    result_dict['data'] = record_dict
    result_dict['invalid'] = invalid_dict
    return result_dict






